﻿#region Using Directives
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
#endregion

namespace DarkMatter.Chat
{
    [DebuggerDisplay("Source = {Source}, MessageType = {MessageType}, Payload = {ToString()}")]
    public class Message
    {
        private static MessageFactory MessageFactory = new MessageFactory(new ChatUser("", ""));

        public Message(ChatUser source, string messageType, byte[] payload)
        {
            Source = source;
            MessageType = messageType;
            Payload = payload;
        }

        public ChatUser Source { get; set; }
        public string MessageType { get; set; }
        public byte[] Payload { get; set; }

        public override string ToString()
        {
            if (MessageType == "TEXT" || MessageType == "INFO")
            {
                return MessageFactory.Encoding.GetString(Payload);
            }

            return "Binary Data";
        }
    }

    public interface IMessageFactory
    {
        Encoding Encoding { get; }
        ChatUser CurrentUser { get; }
        Message TextMessage(string text);
        Message BinaryMessage(byte[] bytes);
        Message InfoMessage(string message, string value);
    }

    public class MessageFactory : IMessageFactory
    {
        private readonly ChatUser _currentUser;
        private readonly Encoding _encoding;

        public MessageFactory(ChatUser currentUser)
        {
            _currentUser = currentUser;
            _encoding = Encoding.UTF8; // should read from config file?
        }

        public MessageFactory(ChatUser currentUser, Encoding encoding)
        {
            _currentUser = currentUser;
            _encoding = encoding;
        }

        public Encoding Encoding
        {
            get { return _encoding; }
        }

        public ChatUser CurrentUser
        {
            get { return _currentUser; }
        }

        public Message TextMessage(string text)
        {
            return new Message(CurrentUser, "TEXT", _encoding.GetBytes(text));
        }

        public Message BinaryMessage(byte[] bytes)
        {
            return new Message(CurrentUser, "BINARY", bytes);
        }

        public Message InfoMessage(string message, string value)
        {
            StringBuilder messageText = new StringBuilder();
            messageText.Append(message);
            if (!string.IsNullOrEmpty(value)) messageText.Append(":" + value);
            return new Message(CurrentUser, "INFO", _encoding.GetBytes(messageText.ToString()));
        }
    }
}

